//index.js
//获取应用实例
const app = getApp()
import {
    createStoreBindings 
} from '../../miniprogram_npm/mobx-miniprogram-bindings/index'
import {store} from '../../store/store'
Page({

    data: {
        advertise: [],
        indicatorDots: true,
        vertical: false,
        autoplay: false,
        interval: 3000,
        duration: 1000,
        menuArray: [],
        menuArrays: [],
        menuArrayss: [],
        hospitalDept: null,
        indexType: '', // 白血病首页 or  血友病首页  or 地贫首页 
        navbarData: {
            title: '首页'
        },
        navHeight: app.globalData.statusBarHeight * 2 + 82,
        userList: null,
        messageList: null,
        current: null,
        titleMessage: null,
        retryTime: 0,
        load: 2000,
        domain: app.globalData.config.educationServer,
        ageKnowledges: [],
        is_review: false,
        healthCheckNo:'',
        tenantId:'',
        count:0
    },
    // 页面显示
    onLoad: function (options) {
        
        wx.showLoading({
            title: '加载中',
            mask: true
        })
        this.storeBindings = createStoreBindings(this, {
            store,
            fields: ["numA", "numB", "sum"],
            actions:{
                getUnRead:'getUnRead'
            },
          });
          
        // if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        //     this.getTabBar().setPath();
        // }
    },
    onUnload() {
        this.storeBindings.destroyStoreBindings();
      },
    getMenu: function () {
        var that = this;
        if (this.data.retryTime < 4) {
            wx.request({
                url: app.getUrl('/xcx/pt/getQueueMenu'),
                method: 'GET',
                header: wx.getStorageSync('cookie'),
                data: {
                    queueId: app.globalData.queueId,
                    type: 1
                },
                success(res) {
                    if (res.data.code == 0) {
                        var menuArray1 = res.data.data;
                        wx.request({
                            url: app.getUrl('/xcx/pt/getQueueMenu'),
                            method: 'GET',
                            header: wx.getStorageSync('cookie'),
                            data: {
                                queueId: app.globalData.queueId,
                                type: 3
                            },
                            success(res) {
                                if (res.data.code == 0) {
                                    var menuArray2 = menuArray1.concat(res.data.data);
                                    wx.request({
                                        url: app.getUrl('/xcx/pt/getQueueMenu'),
                                        method: 'GET',
                                        header: wx.getStorageSync('cookie'),
                                        data: {
                                            queueId: app.globalData.queueId,
                                            type: 4
                                        },
                                        success(res) {
                                            if (res.data.code == 0) {
                                                // var menuArray3 = menuArray2.concat(res.data.data);
                                                // var menuArray4 = menuArray3.filter(item => item.menuName == "诊后指导" || item.menuName == "体格自评"||item.menuName == "线上测评")
                                                // var menuArray5 = menuArray3
                                                // var menuArray6 = menuArray3.filter(item => item.menuName == "评测报告" )
                                                // that.setData({
                                                //     menuArray: menuArray4.sort(function (a, b) {
                                                //         return a.sort - b.sort;
                                                //     }),
                                                //     menuArrays: menuArray5.sort(function (a, b) {
                                                //       return a.sort - b.sort;
                                                //     }),
                                                //     menuArrayss: menuArray6.sort(function (a, b) {
                                                //       return a.sort - b.sort;
                                                //     })
                                                // })
                                                wx.hideLoading();
                                            } 
                                        }
                                    })
                                   
                                } else if (res.data.code == 401) {
                                    app.login(app);
                                    that.data.retryTime++;
                                    that.getMenu();
                                } else {
                                    wx.hideLoading();
                                }
                            }
                        })
                        wx.hideLoading();
                    } else if (res.data.code == 401) {
                        app.login(app);
                        that.data.retryTime++;
                        that.getMenu();
                    } else {
                        that.setData({
                            menuArray: null
                        })
                        wx.hideLoading();
                    }
                }
            })
        } else {
            wx.showToast({
                title: '网络连接异常，请稍后重试',
                icon: 'none'
            })
        }
    },

    getMenus:function(){
      var that = this;
      if (this.data.retryTime < 4) {
        console.log("app.globalData======",app.globalData);
        wx.request({
          url: app.getUrl('/xcx/pt/getQueueMenu'),
          method: 'GET',
          header: wx.getStorageSync('cookie'),
          data: {
              queueId: app.globalData.queueId,
          },
          success(res){
            if (res.data.code == 0) {
              var menuArrays = res.data.data;
              console.log("menuArrays=======",menuArrays);
              menuArrays.forEach(item=>{
                var menuType1 = menuArrays.filter(item =>  item.menuName =="评测报告"|| item.menuName =="体格自评"|| item.menuName =="线上测评")
                var menuType2 = menuArrays.filter( item => item.menuName =="康复周期"|| item.menuName =="就医网点"|| item.menuName =="评估报告" || item.menuName =="科室宣教")
                var menuType3 = menuArrays.filter(item =>  item.menuName =="诊后指导"|| item.menuName =="治疗方案"|| item.menuName =="治疗卡")
                  that.setData({
                    menuArray: menuType1.sort(function (a, b) {
                        return a.sort - b.sort;
                    }),  
                    menuArrays: menuType2.sort(function (a, b) {
                      return a.sort - b.sort;
                    }),  
                    menuArrayss: menuType3.sort(function (a, b) {
                     return a.sort - b.sort;
                    }),                      
                  })
              })
              wx.hideLoading();
            }





          }
        })
          
      }
    },


    getAdv: function () {
        var that = this;
        wx.request({
            url: app.getUrl('/xcx/advertise/queryAdvertises'),
            method: 'GET',
            header: wx.getStorageSync('cookie'),
            success(res) {
                if (res.data.data) {
                    that.setData({
                        advertise: res.data.data
                    })
                }
            }
        })
    },
    getEducation: function () {
        var that = this;
        wx.request({
            url: app.getEducationUrl('/xcx/education/queryEducationContent'),
            method: 'GET',
            header: wx.getStorageSync('cookie'),
            data: {
                sceneId: "hot",
                pageSize: 3
            },
            success(res) {
                var education = res.data.data.data;
                for (var i = 0; i < education.length; i++) {
                    var imgUrls = education[i].imgUrlList;
                    for (var j = 0; j < imgUrls.length; j++) {
                        if (imgUrls[j].indexOf("http") == -1) {
                            imgUrls[j] = that.data.domain + imgUrls[j];
                        }
                    }
                }
                that.setData({
                    knowledgeContents: education
                })
            }
        })
    },
    getAgeEducation: function () {
        var that = this;
        wx.request({
            url: app.getEducationUrl('/xcx/education/queryAgeEducationContent'),
            method: 'GET',
            header: wx.getStorageSync('cookie'),
            data: {
                pageSize: 3,
                userId: app.globalData.userId
            },
            success(res) {
                if (!res.data.data || typeof res.data.data === 'string') return
                var education = res.data.data.data;
                for (var i = 0; i < education.length; i++) {
                    var imgUrls = education[i].imgUrlList;
                    for (var j = 0; j < imgUrls.length; j++) {
                        if (imgUrls[j].indexOf("http") == -1) {
                            imgUrls[j] = that.data.domain + imgUrls[j];
                        }
                    }
                }
                that.setData({
                    ageKnowledges: education
                })
            }
        })
    },
    completemessage:function(data){
      
    },
    getDeptInfo: function () {
        var that = this;
        wx.request({
            url: app.getUrl('/xcx/queryHospDept'),
            method: 'GET',
            header: wx.getStorageSync('cookie'),
            data: {
                // deptId: app.globalData.deptId,
                // deptId: "gzykdxfsdsyydept001"
                deptId:"jmszxyydept001"
            },
            success(res) {
                if (res.data.code == 0) {
                    that.setData({
                        hospitalDept: res.data.data,
                        titleMessage: null,
                    })
                 
                } else if (res.data.code == 401) {
                    //  app.login(app);
                    if(that.data.count<7){
                        setTimeout(function () {
                            that.data.count++; // 先递增
                            that.setData({
                                count: that.data.count // 再赋值
                            });
                            app.login(app);
                          }, 800)
                         
                    }else{
                        wx.showToast({
                            title: '请重新扫码登录',
                            icon: 'none',
                            duration: 2000,
                          })
                        return 
                    }
                } else {
                    if (res.data.message != "OK") {
                        that.setData({
                            titleMessage: res.data.message
                        })
                    }
                }
            }
        })
    },
    getMessage: function () {
        var that = this;
        wx.request({
            url: app.getUrl('/xcx/pt/userNoReadMessage'),
            method: 'GET',
            header: wx.getStorageSync('cookie'),
            success(res) {
                let messageList = res.data.data;
                if (messageList) {
                   
                        wx.showTabBarRedDot({
                            index: 1,
                            success(res) {
                                console.log(res)
                            }
                        })
                    
                    that.setData({
                        messageList: messageList,
                        current: messageList[0]
                    })
                } else {
                    wx.hideTabBarRedDot({
                        index: 1,
                        success(res) {
                            console.log(res)
                        }
                    })
                    that.setData({
                        messageList: null
                    })
                }
            }
        })
    },
    getHospital() {
        let that = this
        wx.request({
            url: app.getUrl('/xcx/queryHospDept'),
            method: 'GET',
            data: {
                deptId: app.globalData.deptId
            },
            header: wx.getStorageSync('cookie'),
            success(res) {
                if (res.data.code == 0) {
                    app.globalData.hospitalInfo = res.data.data
             
                    console.log('res.data.data', res.data.data)
                }
            }
        })
    },

    onShow() {
       this.getUnRead()
    //    this.getTabBar().show()
    //    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
    //         this.getTabBar().setData({
    //             selected : 0
    //         })
    //     }
    
        var that = this;
        setTimeout(function () {
            that.data.load = 100;
            that.data.retryTime = 0;
            if (wx.getStorageSync('cookie') && app.globalData.definedUrl) {
                // that.getMenu();
                that.getMenus();
                that.getAdv();
                that.getEducation();
                that.getDeptInfo();
                that.getMessage();
                that.getAgeEducation();
                that.getCurrentUserInfo()
                that.getHospitalInfo()
                that.getUserInfo()
                that.setData({
                    is_review: app.globalData.queueId.indexOf('YZDL') > -1
                })
            } else {
                let timer = setTimeout(function () {
                    app.login().then(() => {
                        // that.getMenu();
                        that.getMenus();
                        that.getAdv();
                        that.getEducation();
                        that.getDeptInfo();
                        that.getMessage();
                        that.getAgeEducation();
                        that.getUserInfo()
                    });
                }, 600);
            }
        }, that.data.load);
    },

    //事件处理函数
    bindViewTap: function () {
        wx.navigateTo({
            url: '../logs/logs'
        })
    },

    bindMenuTap: function (e) {
        var that = this;
        wx.request({
            url: app.getUrl('/xcx/menu/click'),
            method: 'GET',
            header: wx.getStorageSync('cookie'),
            data: {
                id: e.currentTarget.dataset.id
            },
            success(res) {
                that.setData({})
            }
        })
        wx.navigateTo({
            url: e.currentTarget.dataset.url
        })
    },
    toQueue: function (e) {
        wx.request({
            url: app.getUrl('/xcx/pt/getUsersInfo'),
            method: 'GET',
            header: wx.getStorageSync('cookie'),
            success(res) {
                if (res.data.code == 0) {
                    app.globalData.userList = res.data.data
                    wx.navigateTo({
                        url: '../guide/user_list/userList',
                    })
                   
                    
                } else if (res.data.code == 200) {
                    wx.navigateTo({
                        url: "../guide/queue_list/queueList?ptUserId=" + res.data.data[0].id,
                    })
                } else if (res.data.code == 404) {
                    wx.navigateTo({
                        url: '../guide/queue/queue?code=true',
                    })
                }
            }
        })
    },
    getUserInfo:function(){
        let that =this

        let {openid,accountId} = wx.getStorageSync('logindata')
        wx.request({
            // url: app.getUrl('/xcx/pt/getUsersInfo'),
            url: app.getUrl(`/xcx/pt/getUsersInfoByOpenId?openId=${openid}&accountId=${accountId}`),
            method: 'GET',
            header: wx.getStorageSync('cookie'),
            success(res) {
                if (res.data.code == 0  || res.data.code == 200) {
                    console.log('用户', res.data.data )
                    console.log('切',app.globalData)
                     let userId = app.globalData.userId
                    //  const {  healthCheckNo,tenantId } = res.data.data.filter(item=>{
                    //      return item.id == userId
                    //  })[0];
                    const newUser = res.data.data.filter(item=>{
                        return item.id == userId
                    })[0];     
                     console.log('healthCheckNo',newUser.healthCheckNo)
                     that.setData({
                         healthCheckNo:newUser.healthCheckNo,
                         tenantId:newUser.tenantId
                     })
                    app.globalData.userList = res.data.data 
                } 
            }
        })
    },
    toKnowledgeDetail: function (e) {
        wx.navigateTo({
            url: "../knowledge/knowledgeDetail/knowledgeDetail?id=" + e.currentTarget.dataset.id + "&channel=" + e.currentTarget.dataset.channel
        })
    },
    toMoreKnowledge: function () {
      wx.navigateTo({
        url: '../knowledge/knowledge',
      })
        // wx.switchTab({
        //     url: "/pages/knowledge/knowledge"
        // })
    },
    // 前往消息
    toMessage: function (e) {
        var that = this;
        wx.request({
            url: app.getUrl('/xcx/pt/messageRead'),
            method: 'GET',
            header: wx.getStorageSync('cookie'),
            data: {
                messageId: e.currentTarget.dataset.id
            },
            success(res) {
                that.setData({
                    messageList: res.data.data
                })
            },
            complete: function () {
                wx.navigateTo({
                    url: e.currentTarget.dataset.url,
                })
            }
        })

    },
    toAdvertise: function (e) {
        var that = this;
        wx.request({
            url: app.getUrl('/xcx/advertise/read'),
            method: 'GET',
            header: wx.getStorageSync('cookie'),
            data: {
                id: e.currentTarget.dataset.id
            },
        })

        // 小程序跳转小程序 
        console.log(e.currentTarget.dataset)
        if (e.currentTarget.dataset.type == 1) {
            wx.navigateToMiniProgram({
                appId: e.currentTarget.dataset.appid, // 要跳转的小程序的appid
                // appId: 'wxdf6f8dd9a818c9b3',
                path: e.currentTarget.dataset.url, // 跳转的目标页面
                // path: '/pages/goods/goods?id=1181028',
                // extarData: {
                //   open: 'auth',
                //   id: '1181028'
                // },
                success(res) {
                    console.log(res)
                }
            })
        } else if (e.currentTarget.dataset.type == 2) {
          
            wx.navigateTo({
                url: "/pages/advertise/advertise?url=" + e.currentTarget.dataset.url
            })
        }
    },
    
    bindWebMenuTap: function (e) {
        console.log('e111', e)
        var that = this;
        wx.request({
            url: app.getUrl('/xcx/menu/click'),
            method: 'GET',
            header: wx.getStorageSync('cookie'),
            data: {
                id: e.currentTarget.dataset.id
            },
            success(res) {}
        })
        let param = `url=${ e.currentTarget.dataset.url }`
        console.log('param', param)
        // if (e.currentTarget.dataset.url.indexOf('scale/onlinEevaluation') > -1) {
        //     param += '&type=scaleList'
        // }
        if (e.currentTarget.dataset.url.indexOf('scale/html/report_list.html') > -1) {
            param += `&type=reportList`
        }
        
        
        wx.navigateTo({
            url: "/pages/advertise/advertise?" + param
            //   url: "/pages/advertise/advertise?" + 'url=http://127.0.0.1:3020/html/list.html&type=scaleList'
        })
    },
    getHospitalInfo: function () {
        // return GET('/xcx/queryHospDept', { deptId: app.globalData.deptId });
        wx.request({
            url: app.getUrl('/xcx/queryHospDept'),
            method: 'GET',
            data: {
                deptId: app.globalData.deptId
            },
            header: wx.getStorageSync('cookie'),
            success(res) {
                if (res.data.code == 0) {
                    app.globalData.hospitalInfo = res.data.data

                }


            }
        })
    },
    getCurrentUserInfo: function () {
        const that = this
        let {openid,accountId} = wx.getStorageSync('logindata')
        wx.request({
            // url: app.getUrl('/xcx/pt/getCurrentUserInfo'),
            url: app.getUrl(`/xcx/pt/getCurrentUserInfo?openId=${openid}&accountId=${accountId}`),
            method: 'GET',
            header: wx.getStorageSync('cookie'),
            success(res) {
                if (res.data.code !== 0) return
                app.globalData.currentPatient = res.data.data
            }
        })
    },
})